﻿using System;
using System.Drawing.Printing;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;

namespace Common
{
    public class PrintUtil
    {
        public static void SendToPrinter(string filename, PrinterSettings printerSettings)
        {
            Excel.Application excelApp = new Excel.Application();

            // Open the Workbook:
            Excel.Workbook wb = excelApp.Workbooks.Open(
                filename,
                Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                Type.Missing, Type.Missing, Type.Missing, Type.Missing);

            // Get the first worksheet.
            // (Excel uses base 1 indexing, not base 0.)
            Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets[1];

            // Print out 1 copy to the selected printer:
            ws.PrintOut(
                Type.Missing, Type.Missing, printerSettings.Copies, Type.Missing,
                printerSettings.PrinterName, printerSettings.PrintToFile, printerSettings.Collate, 
                filename);

            // Cleanup:
            GC.Collect();
            GC.WaitForPendingFinalizers();

            Marshal.FinalReleaseComObject(ws);

            wb.Close(false, Type.Missing, Type.Missing);
            Marshal.FinalReleaseComObject(wb);

            excelApp.Quit();
            Marshal.FinalReleaseComObject(excelApp);
        }
    }
}
